package org.springblade.flow.repair.parts.service.impl;

import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.task.Comment;
import org.springblade.common.cache.UserCache;
import org.springblade.common.config.ProjectApiConfiguration;
import org.springblade.core.tool.utils.*;
import org.springblade.flow.business.service.IFlowService;
import org.springblade.flow.core.entity.BladeFlow;
import org.springblade.flow.core.utils.TaskUtil;
import org.springblade.flow.engine.constant.FlowEngineConstant;
import org.springblade.flow.repair.parts.service.IPartsService;
import org.springblade.modules.admin.dto.PartsWorkSaveDTO;
import org.springblade.modules.admin.enums.SourceEnum;
import org.springblade.modules.admin.utils.AsyncUtils;
import org.springblade.modules.system.entity.User;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

import static org.springblade.flow.repair.parts.constant.PartsProcessConstant.PARTS_HISTORY_TASK;

/**
 * @Description
 * @Author ysq
 * @Date 2022/6/28
 **/

@Slf4j
@Service
@AllArgsConstructor
public class PartsServiceImpl implements IPartsService {

	private final IFlowService flowService;
	private final AsyncUtils asyncUtils;
	private final ProjectApiConfiguration projectApiConfiguration;

	@Override
	public List<BladeFlow> historyFlowList(String processInstanceId) {
		List<BladeFlow> flowList = new LinkedList<>();
		List<HistoricActivityInstance> historicActivityInstanceList = flowService.historyFlowList(processInstanceId);
		// 正在运行（未审批）的节点
		List<HistoricActivityInstance> curTaskList = new ArrayList<>();
		Arrays.sort(PARTS_HISTORY_TASK);
		for (int i = 0; i < historicActivityInstanceList.size(); i++) {
			HistoricActivityInstance historicActivityInstance = historicActivityInstanceList.get(i);
			// 过滤非处理人节点
			if ("MI_END".equals(historicActivityInstance.getDeleteReason())) {
				continue;
			}
			// 显示开始节点和结束节点，并且执行人不为空的任务
			if (Arrays.binarySearch(PARTS_HISTORY_TASK, historicActivityInstance.getActivityId()) >= 0) {
				if (Func.isEmpty(historicActivityInstance.getEndTime())) {
					curTaskList.add(historicActivityInstance);
					continue;
				}
				BladeFlow flow = new BladeFlow();
				flow.setHistoryActivityId(historicActivityInstance.getActivityId());
				flow.setHistoryActivityName(historicActivityInstance.getActivityName());
				flow.setCreateTime(historicActivityInstance.getStartTime());
				flow.setEndTime(historicActivityInstance.getEndTime());
				String durationTime = DateUtil.secondToTime(Func.toLong(historicActivityInstance.getDurationInMillis(), 0L) / 1000);
				flow.setHistoryActivityDurationTime(durationTime);
				// 获取流程发起人名称
				if (FlowEngineConstant.START_EVENT.equals(historicActivityInstance.getActivityType())) {
					List<HistoricProcessInstance> processInstanceList = flowService.processInstanceList(processInstanceId);
					if (processInstanceList.size() > 0) {
						if (StringUtil.isNotBlank(processInstanceList.get(0).getStartUserId())) {
							String taskUser = processInstanceList.get(0).getStartUserId();
							User user = UserCache.getUser(TaskUtil.getUserId(taskUser));
							if (user != null) {
								flow.setAssignee(historicActivityInstance.getAssignee());
								flow.setAssigneeName(user.getRealName());
							}
						}
					}
				}
				// 获取任务执行人名称
				if (StringUtil.isNotBlank(historicActivityInstance.getAssignee())) {
					User user = UserCache.getUser(TaskUtil.getUserId(historicActivityInstance.getAssignee()));
					if (user != null) {
						flow.setAssignee(historicActivityInstance.getAssignee());
						flow.setAssigneeName(user.getRealName());
					}
				}
				// 获取意见评论内容
				if (StringUtil.isNotBlank(historicActivityInstance.getTaskId())) {
					List<Comment> commentList = flowService.getTaskComments(historicActivityInstance.getTaskId());
					if (commentList.size() > 0) {
						flow.setComment(commentList.get(0).getFullMessage());
					}
				}
				flowList.add(flow);
			}
		}

		// 处理正在审批的节点
		if (curTaskList.size() > 0) {
			HistoricActivityInstance curActivityInstance = curTaskList.get(0);
			BladeFlow flow = new BladeFlow();
			flow.setHistoryActivityId(curActivityInstance.getActivityId());
			flow.setHistoryActivityName(curActivityInstance.getActivityName());
			flow.setCreateTime(curActivityInstance.getStartTime());
			// 获取任务执行人名称
			List<Long> assigneeList = curTaskList.stream().map(t -> TaskUtil.getUserId(t.getAssignee())).collect(Collectors.toList());
			List<String> assigneeNameList = new ArrayList<>();
			for (Long assignee : assigneeList) {
				User user = UserCache.getUser(assignee);
				if (user != null) {
					assigneeNameList.add(user.getRealName());
				}
			}
			flow.setAssignee(assigneeList.stream().map(t -> String.valueOf(t)).collect(Collectors.joining("、")));
			flow.setAssigneeName(assigneeNameList.stream().collect(Collectors.joining("、")));
			flowList.add(flow);
		}

		return flowList;
	}

	@Override
	public Boolean startProcess(List<PartsWorkSaveDTO> partsWorkSaveList) {
		partsWorkSaveList.forEach(e -> {
			e.setSource(SourceEnum.MANAGEMENT_SIDE.getId());
			asyncUtils.createPost(projectApiConfiguration.getMaintain() + "/blade-flow/parts/start-process", JSONObject.toJSONString(e), WebUtil.getRequest());
		});
		return true;
	}

}
